package net.halflite.mzkr.action.home;

import java.io.FileNotFoundException;
import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.halflite.mzkr.annotation.SessionRequired;
import net.halflite.mzkr.dto.user.ImageDto;
import net.halflite.mzkr.service.UserImageService;

import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;
import org.seasar.framework.container.annotation.tiger.Binding;
import org.seasar.framework.container.annotation.tiger.BindingType;
import org.seasar.struts.annotation.Arg;
import org.seasar.struts.annotation.Execute;
import org.seasar.struts.annotation.Required;
import org.seasar.struts.enums.SaveType;

public class UploadAction extends LoginedBaseAction {

	@Resource
	private HttpServletResponse response;

	@Resource
	private UserImageService userImageService;
	
	@Required(arg0 = @Arg(key = "画像ファイル", resource = false))
    @Binding(bindingType = BindingType.NONE)
    public FormFile formFile;

	/** 入力 */
    @Execute(validator = false)
    public String index() {
        return "index.jsp";
    }

    /** 
     * アップロード 
     * @throws IOException 
     * @throws FileNotFoundException */
    @Execute(validate = "validate", saveErrors = SaveType.SESSION, input = "./?redirect=true")
    public String upload() throws FileNotFoundException, IOException {
    	sessionScope.put("uploadImage", userImageService.upload(formFile));
        return "confirm?redirect=true";
    }

	/** 確認 */
    @SessionRequired(redirect = "./", keys = "uploadImage")
    @Execute(validator = false)
    public String confirm() {
        return "confirm.jsp";
    }

	/** 入力画面に戻る */
    @Execute(validator = false)
    public String back() {
        return "./?redirect=true";
    }

	/** 登録 
	 * @throws IOException */
    @SessionRequired(redirect = "./", keys = "uploadImage")
    @Execute(validator = false)
    public String post() throws IOException {
    	ImageDto dto = (ImageDto) sessionScope.get("uploadImage");
    	userImageService.post(findUserId(), dto);
        return "success?redirect=true";
    }

	/** 完了 */
    @Execute(validator = false)
    public String success() {
    	sessionScope.remove("uploadImage");
        return "success.jsp";
    }

    
	/** アップロードしたファイル表示 
	 * @throws IOException 
	 */
    @Execute(validator = false)
    public String image() throws IOException {
    	ImageDto dto = (ImageDto) sessionScope.get("uploadImage");
    	dto.setResponse(response);
        return null;
    }

    /** 選択したファイル検証 */
    public ActionMessages validate() {
    	return userImageService.validateFormFile(formFile);
    }
}
